<template>
	<view>
		<!-- <u-navbar :title="title" :custom-back="back"></u-navbar> -->
		<u-tabs ref="tabs" :list="listTip" :scrollable="false" @change="tabschange"></u-tabs>

		<view>
			<scroll-view scroll-y="true" class="scroll-Y" :refresher-triggered="
				triggered" refresher-background="#f4f7f8" @scrolltolower="onPulling" refresher-enabled="true"
				@refresherrefresh="onRefresh" refresher-default-style="black">
				<view v-if='isChargeOrder'>
					<view v-for="item in showlist" class="bg" @click="itemxqtap(item)">
						<view class="container">
							<!--  -->
							<view class="radio" :class="[itemisactive(item)]" @click.stop="itemtap(item)"></view>
							<view class="box">
								<view class="box-item order-number">
									订单编号：{{item.ddh}}

								</view>
								<view class="box-item">
									<span v-if="item.sjyys">预约充电时间：</span>
									<span v-else>充电时间：</span>
									{{item.sjcds}}

								</view>
								<view class="box-item">
									站点名称：{{item.pcsxs}}
								</view>
								<!-- <view class="box-item">
									金额：{{item.je / 100}}元
								</view> -->
								<view class="box-item">
									<text class="tkspan" v-if="item.sjtk">{{ $z.$t("已退款") }}</text>
									<text v-else>金额：</text>
									{{ item.je / 100 }}{{ $z.$t("元") }}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else>
					<view class="bg" v-for="(item, key) in parkingLockList" :key="key" @click="itemtap(item)">
						<!-- <view class="ddh u-flex u-flex-between">
							<view class="u-line-1" style="flex: 1;">{{$z.$t("订单编号")}}：{{ item.ddh }}</view>
							<u-button type="primary" v-if="item.b_zf == 1" text="已完成" style="width: auto; margin: 0"
								size="mini"></u-button>
							<u-button type="error" v-else text="未支付" style="width: auto; margin: 0"
								size="mini"></u-button>
						</view> -->
						<view class="container">
							<view class="radio" :class="[itemisactive(item)]" @click.stop="itemtap(item)"></view>
							<view class="box">
								<view class="box-item order-number">
									订单编号：{{item.ddh}}
								</view>
								<view class="box-item">
									{{$z.$t("占位时间")}}：
									{{item.sjs}}

								</view>
								<view class="box-item">
									{{$z.$t("站点名称")}}：
									{{ item.pcsmc }}
								</view>
								<!-- 字段是支付金额 -->
								<view class="box-item">
									{{$z.$t("占位费")}}：
									{{item.jesj / 100 ? item.jesj / 100 : 0}}元
								</view>
							</view>

						</view>

					</view>
				</view>

				<u-loadmore :status="status" marginBottom="10" />
			</scroll-view>

			<fixedbtn>
				<view class="fixedbtnbox">
					<u-button type="primary" :loading="loading" :disabled="activeddh.length == 0" @click="fpfromshow">
						{{$z.$t("开取发票")}}
					</u-button>
				</view>
			</fixedbtn>
			<u-datetime-picker v-model="defaultTime" :show="show" mode="datetime" @cancel="close"
				@confirm="confirm"></u-datetime-picker>
			<fpfrom ref="fpfrom"></fpfrom>
		</view>
	</view>

</template>

<script>
	import qs from "qs";

	import fpfrom from "./components/fpfrom.vue";

	export default {
		components: {
			fpfrom,
		},
		data() {
			return {
				chargeTimes: {}, // 用于存储充电时间
				ddh: '', //充电的ddh订单号
				status: "loadmore",
				triggered: false,
				loading: false,
				title: this.$z.$t("申请开票"),
				// 组件内部parmas参数默认值：
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
					province: true,
					city: true,
					area: true,
					timestamp: true, // 1.3.7版本提供
				},
				mode: "",
				show: false,
				fromdata: {},
				defaultTime: "",
				tapkey: "",
				searchdata: [],

				page: "page",
				tapitem: {},
				ReccdSQselect: [],
				umodaldata: {},
				activeddh: [],
				list: [],
				showlist: [],
				listTip: [{
						name: this.$z.$t("充电订单"),
					},
					{
						name: this.$z.$t("占位订单"),
					},
					// {
					// 	name: this.$z.$t("进行中"),
					// },
				],
				current: 1,
				isChargeOrder: true,
				parkingLockList: [],
			};
		},
		// mixins: [settingvue],
		onLoad(query) {
			// title:"充电记录",
			// if (query.type == "sy") {
			// 	this.title = this.$z.$t("在线申诉");
			// }
			this.current = 1
			this.init(this.current);
			console.log('showlist', this.showlist);
		},
		computed: {
			reqdata() {
				let r = {
					sjs: `${this.$z.timefn.gettime(360)} 00:00:00`,
					sje: `${this.$z.timefn.gettime("-1")} 00:00:00`,
				};
				r.csta = this.list.length;
				r.cmax = 10;
				r.uUser = this.$store.state.user.USearch.uUser
				r.b_tk = "1";
				r.b_end = "1";
				return r;
			},
			reqdataParams() {
				let r = {
					sjs: `${this.$z.timefn.gettime(360)} 00:00:00`,
					sje: `${this.$z.timefn.gettime("-1")} 00:00:00`,
				};
				r.csta = this.parkingLockList.length;
				r.cmax = 10;
				r.b_end = 1;
				return r;
			},
		},
		methods: {
			async tabschange(val) {
				console.log('val', val);

				if (val.index == 0) {
					this.current = 1
					this.isChargeOrder = true
					await this.init(this.current)
				} else {
					console.log('222');
					this.isChargeOrder = false
					// this.showlist = [];
					this.current = 2
					await this.getParkingLockdata()

				}
			},
			async getParkingLockdata() {
				if (!this.$store.state.user.USearch.uUser) {
					await this.$store.dispatch("user/getuser");
				}
				let USearch = this.$store.state.user.USearch;
				let reqdata = {
					...this.reqdataParams,
					uUser: USearch.uUser,
				};
				let ChargeUserDs = await this.$z.request("/ChargeUserDs", reqdata);
				ChargeUserDs = ChargeUserDs.filter(item => {
					const shouldFilter = (
						item.b_zf == 0 ||
						(Number(item.jesj) > 0 && Number(item.je) == 0) ||
						Number(item.jesj) == 0 ||
						item.zftype == 3
					);
					return !shouldFilter; // 保留不符合上述条件的数据
				});
				console.log('ChargeUserDs22', ChargeUserDs);
				if (ChargeUserDs.length != 0) {
					let reqdata = {};
					reqdata.ddhsum = ChargeUserDs.length;
					ChargeUserDs.forEach((e, i) => {
						reqdata[`ddh${i + 1}`] = e.ddh;
					});
					let FPcdListddh = await this.$z.request("/FPcdListddh", reqdata);
					FPcdListddh = FPcdListddh.map((e) => e.ddh);
					ChargeUserDs = ChargeUserDs.filter((e) => {
						return !FPcdListddh.includes(e.ddh);
					});
				}

				// 过滤掉已经存在于 parkingLockList 的数据
				ChargeUserDs = ChargeUserDs.filter(newItem =>
					!this.parkingLockList.some(existingItem => existingItem.ddh === newItem.ddh)
				);

				this.parkingLockList = this.parkingLockList.concat(ChargeUserDs);
				this.status = ChargeUserDs.length >= this.reqdata.cmax ? "loadmore" : "nomore";
				await this.fetchChargeTimes(); // 获取充电时间
			},
			async fetchChargeTimes() {
				for (const item of this.parkingLockList) {
					if (Number(item.je) > 0) {
						const chargeTime = await this.searchChargeTime(item);
						this.$set(this.chargeTimes, item.ddh, chargeTime);
					}
				}
			},
			async searchChargeTime(val) {
				console.log('到这了吗');
				let ChargeUserDsToUser = await this.$z.request("/ChargeUserDsToUser", {
					ddhds: val.ddh
				});
				if (ChargeUserDsToUser.length > 0) {
					let GetRfCD = await this.$z.request("/GetRfCD", {
						ddh: ChargeUserDsToUser[0].ddh
					});
					if (GetRfCD.length > 0) {
						return GetRfCD[0].sjcds;
					} else {
						return '-';
					}
				}
			},
			async onPulling() {
				console.log('为什么没触发');
				// 滚动到底部
				console.log('this.status', this.status);
				if (this.status == "loading" || this.status == "nomore") {
					return;
				}
				this.status = "loading";
				if (this.current == 1) {
					await this.getdata()
				} else {

					await this.getParkingLockdata()
				}

			},
			async onRefresh() {
				console.log('this.current', this.current);
				if (this.current == 1) {
					// 下拉刷新
					if (this.status == "loading") {
						return;
					}
					this.status = "loading";
					this.triggered = true;
					this.list = [];
					this.showlist = [];
					await this.getdata()
					this.triggered = false;
				} else {
					if (this.status == "loading") {
						return;
					}
					this.status = "loading";
					this.triggered = true;

					await this.getParkingLockdata()
					this.triggered = false;
				}

			},
			close() {
				this.show = false;
			},
			gofp() {
				uni.navigateTo({
					url: "/pages/batteryRecords/FPcdadd/FPcdadd",
				});
			},
			dlfn(p) {
				var num = p.dl / 10000;
				return num.toFixed(2);
			},
			ReccdSQaddfn() {
				let querydata = {};
				if (this.ReccdSQselect.length == 0) {
					querydata = this.tapitem;
				} else {
					querydata = this.ReccdSQselect[0];
				}
				querydata.ddje = this.tapitem.je;
				uni.$z.gopage(
					"/pages/batteryRecords/ReccdSQadd/ReccdSQadd?" +
					qs.stringify(querydata)
				);
			},
			back() {
				if (this.page != "page") {
					this.page = "page";
				} else {
					uni.navigateBack();
				}
			},
			async ReccdSQdelbtnfn() {
				this.umodaldata = {
					show: true,
					content: "取消申诉",
					showTitle: false,
					showCancelButton: true,
					updatafn: async () => {
						let par = await uni.$z.request(
							"/ReccdSQdel",
							this.ReccdSQselect[0]
						);
						if (par[0].par == "succeed") {
							this.searchfn();
						} else {
							let str = config.pars[par[0].par] || "";
							this.umodaldata = {
								show: true,
								content: str,
								showTitle: false,
							};
						}
						// uni.$z.sys();
					},
				};
			},
			ReccdSQfalgfn(e) {
				if (e["je"] == 0) {
					return false;
				}
				if (e["sjtk"]) {
					return false;
				}
				let t = Math.ceil(uni.$z.timefn.getUTCtime(e["sjc"]) / 60 / 24);
				if (t >= 30) {
					return false;
				}
				if (e["sjcds"] && e["sjcde"]) {
					if (e["type"] == 1 || e["type"] == 3) {
						if (this.ReccdSQselect.length != 0) {
							return this.ReccdSQselect[0];
						} else {
							return "n";
						}
					}
					var cdsj = e.cdsj;
					var sjsj = uni.$z.timefn.getUTCtime(e.sjcds, e.sjcde);
					if (cdsj - sjsj > 10 && sjsj > 2) {
						if (this.ReccdSQselect.length != 0) {
							return this.ReccdSQselect[0];
						} else {
							return "n";
						}
					} else {
						return false;
					}
				} else {
					return false;
				}
			},
			async zdxqfn(item) {
				this.tapitem = item;
				let ReccdSQ = await uni.$z.request("/ReccdSQ", {
					...item,
				});
				this.ReccdSQselect = ReccdSQ;
				this.page = "pagexq";
			},
			timetap(item) {
				console.log(123456);
				let str = this.fromdata[item];
				this.tapkey = item;
				this.defaultTime = str;
				this.show = true;
			},
			confirm(data) {
				this.fromdata[this.tapkey] = data.t;
				this.show = false;
			},
			async init() {
				await this.$store.dispatch("user/getuser");
				this.getdata();

			},
			async getdata(len = 10, reqdatas = []) {
				this.loading = true;
				let data = await uni.$z.request(
					"/GetRfCD",
					this.reqdata,
					"POST",
					"json",
					true
				);
				this.list = this.list.concat(data);
				console.log('this.list', this.list)
				let showlist = data.filter((e) => {
					return e.ddh && e.ddh != "null" && e.type == "31" && e.je != "0";
				});
				if (showlist.length != 0) {
					let reqdata = {};
					reqdata.ddhsum = showlist.length;
					showlist.forEach((e, i) => {
						reqdata[`ddh${i + 1}`] = e.ddh;
					});
					let FPcdListddh = await this.$z.request("/FPcdListddh", reqdata);
					FPcdListddh = FPcdListddh.map((e) => e.ddh);
					showlist = showlist.filter((e) => {
						return !FPcdListddh.includes(e.ddh);
					});
				}
				this.loading = false;
				this.page = "page";
				showlist = showlist.reverse();
				let gtels = showlist.map(function(e) {
					return e.gtel;
				});
				gtels = new Set(gtels);
				let reqdata = {
					gtelsum: gtels.size,
				};
				[...gtels].forEach(function(e, i) {
					reqdata[`gtel${i + 1}`] = e;
				});

				for (let i = 0; i < showlist.length; i++) {
					let ChargeCar = await this.$store.dispatch("request/getRequest", {
						url: "/ChargeCar",
						data: {
							gtel: showlist[i].gtel
						}
					});
					console.log('ChargeCar', ChargeCar);
					// 检查 ChargeCar 是否为空
					if (!ChargeCar || ChargeCar.length === 0) {
						console.warn(`未找到 gtel 为 ${showlist[i].gtel} 的 ChargeCar 数据`);
						continue; // 跳过当前循环
					}

					let Station = await this.$store.dispatch("request/getRequest", {
						url: "/Station",
						data: {
							id: ChargeCar[0].pcs
						}
					});

					// 检查 Station 是否为空
					if (!Station || Station.length === 0) {
						console.warn(`未找到 pcs 为 ${ChargeCar[0].pcs} 的 Station 数据`);
						continue; // 跳过当前循环
					}

					showlist[i].pcsxs = Station[0].pcs;
				}
				this.showlist.sort((a, b) => {
					// 将日期字符串转换为时间戳进行比较
					const timestampA = new Date(a.sjcde).getTime();
					const timestampB = new Date(b.sjcde).getTime();

					// 倒序排列（最新日期在前）
					return timestampB - timestampA;
				});
				this.showlist = this.showlist.concat(showlist);
				console.log('showlist11', this.showlist);
				reqdatas = reqdatas.concat(showlist);

				if (data.length == len && reqdatas.length < len) {
					await this.getdata(len, reqdatas);
				} else {
					this.status = "loadmore";
				}
				if (data.length < len) {
					this.status = "nomore";
				}
			},
			itemisactive(item) {
				let i = this.activeddh.findIndex((e) => {
					return e.ddh == item.ddh;
				});
				return i == -1 ? [] : ["active"];
			},
			itemtap(item) {
				let i = this.activeddh.findIndex((e) => {
					return e.ddh == item.ddh;
				});
				// console.log(111111);
				if (i == -1) {
					this.activeddh.push(item);
				} else {
					this.activeddh.splice(i, 1);
				}
			},
			itemxqtap(item) {
				uni.navigateTo({
					url: `/pages/order/ddxq/ddxq?${qs.stringify(item)}`
				})
			},
			async fpfromshow() {
				let reqdata = {};
				reqdata.ddhsum = this.activeddh.length;
				this.activeddh.forEach((e, i) => {
					reqdata[`ddh${i + 1}`] = e.ddh;
				});
				this.loading = true;
				await this.$z.request("/FPcdListddh", reqdata);
				this.loading = false;
				console.log('this.activeddh', this.activeddh);
				this.$refs.fpfrom.show(this.activeddh, this.current);
			},
			FPcddowfn() {
				uni.navigateTo({
					url: "/pages/batteryRecords/FPcddow/FPcddow",
				});
			},
		},
	};
</script>

<style lang="scss">
	.tkspan {
		background-color: #dd524d;
		font-size: 12px;
		line-height: 1;
		display: inline-block;
		padding: 3px 6px;
		color: #ffffff;
		border-radius: 100px;
	}

	.radio {
		width: 50rpx;
		height: 50rpx;
		border: 4rpx solid #aaa;
		border-radius: 50%;
		// padding: 0 0rpx;
		// margin-right: 30rpx;

		&.active {
			position: relative;
			border-color: #2093f5;
			display: flex;
			justify-content: center;
			align-items: center;

			&::after {
				content: "";
				width: 26rpx;
				height: 26rpx;
				display: block;
				border-radius: 50%;
				background-color: #2093f5;
			}
		}
	}

	.fixedbtnbox {
		width: 100%;
		padding: 0 30rpx;
	}

	.bg {
		background-color: #f4f7f8;
		padding: 20rpx;
	}

	.scroll-Y {
		height: calc(100vh - 250rpx);
	}


	.container {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		background-color: white;
		padding: 20rpx;

		.box-item {
			line-height: 80rpx;
			margin-left: 20rpx;
		}

		.order-number {
			display: inline-block;
			/* 或 block */
			max-width: 600rpx;
			/* 根据容器调整 */
			overflow: hidden;
			/* 隐藏溢出内容 */
			text-overflow: ellipsis;
			/* 显示省略号 */
			white-space: nowrap;
			/* 禁止换行 */
		}
	}
</style>